<?php

class Ext_Db_Date extends Zend_Date {
    const NOW = "NOW";
    private $_is_curr_date;

    public function __construct( $date = null, $part = null, $locale = null ) {
        // Como default uso iso por que es el formato con el cual traigo las fechas
        // desde la base de datos.
        if ( $part === null ) {
            $part = Ext_Db_Date::ISO_8601;
        }
        if ( $date === self::NOW ) {
            $date = null;
        }
        
        $this->_is_curr_date = ( $date === null );
        
        if ( is_null( $date ) ) {
            $date = self::now( $locale );
            if ( ( $part !== null ) && ( $part !== parent::TIMESTAMP ) ) {
                $date = $date->get( $part );
            }
        }
        
        parent::__construct( $date, $part, $locale );
    }

    public function setNow() {
        $this->_is_curr_date = true;
    }

    public function isNow() {
        return $this->_is_curr_date;
    }

    // Override this, try to get the date from the database.
    public static function now( $locale = null ) {
        $db = Zend_Db_Table_Abstract::getDefaultAdapter();
        if ( ! empty( $db ) ) {
            $curDateTime = $db->getCurrDate();
            if ( ! empty( $curDateTime ) ) {
                return new Ext_Db_Date( $curDateTime, Ext_Db_Date::ISO_8601, $locale );
            }
        }
        return parent::now( $locale );
    }

    public static function format( $dbDateString, $format ) {
        $date = new Ext_Db_Date( $dbDateString );
        return $date->toString( $format );
    }

}